import { delItems, getItemList, updateItems } from '@/api';
import { ExtraFields } from '@/constants/extra-fields';
import { rootFieldNames } from '@/constants/materials';
import { UpdateItemsRequest, UpdateType } from '@/types/third-party/api';
import { Button, Flex, message } from 'antd';
import dayjs from 'dayjs';
import { useRef } from 'react';
import { useModel } from 'umi';

export function SyncData() {
  const { orderResult } = useModel('orderInfo');
  const { thirdFieldConfig, linkedOrder } = useModel('fieldConfig');
  const { transformedData, setTransformedData } = useModel('syncData');
  const fieldConfigMapRef = useRef<Record<string, any[]>>({});

  function onTransformData() {
    console.log({ orderResult, thirdFieldConfig });
    const fieldConfigMap: Record<string, any[]> = {};
    Object.keys(thirdFieldConfig).map((tableId) => {
      Object.keys(thirdFieldConfig[tableId]).map((fieldId) => {
        const path = thirdFieldConfig[tableId][fieldId];
        if (path === undefined) {
          return;
        }
        const [rootPath, subPath] = path.split('/');
        if (fieldConfigMap[rootPath] === undefined) {
          fieldConfigMap[rootPath] = [
            { subPath, thirdField: { tableId, fieldId } },
          ];
        } else {
          fieldConfigMap[rootPath].push({
            subPath,
            thirdField: { tableId, fieldId },
          });
        }
      });
    });
    console.log({ fieldMap: fieldConfigMap });
    fieldConfigMapRef.current = fieldConfigMap;

    const orderInfo = orderResult.data;
    if (!orderInfo) {
      message.warning('订单信息为空');
      return;
    }
    const targetNames = rootFieldNames;
    const thirdFields: Record<string, any[]> = {};
    // console.log({ thirdFields });
    orderInfo.map((order) => {
      targetNames.map((targetName) => {
        const rootNode = order[targetName as keyof typeof order] as any[];
        if (rootNode !== undefined) {
          // console.log({ rootNode, thirdFieldConfig });
          rootNode.map((dataItem) => {
            const tables: Record<string, any> = {};
            (fieldConfigMap[targetName] ?? []).map((configItem) => {
              const { tableId, fieldId } = configItem.thirdField;
              const value = dataItem[configItem.subPath];
              let row = tables[tableId];
              if (row === undefined) {
                row = {};
                tables[tableId] = row;
                if (thirdFields[tableId] === undefined) {
                  thirdFields[tableId] = [];
                }
                thirdFields[tableId].push(row);
              }
              row[fieldId] = value;
            });
          });
        }
      });
    });
    const result = thirdFields;
    console.log({ result });
    setTransformedData(result);
  }
  async function onSyncData() {
    const thirdFields = transformedData as Record<string, any[]>;
    await Promise.all(
      Object.keys(thirdFields).map(async (tableId) => {
        const mainFieldId = findFieldId(tableId, ExtraFields.MainFieldId);
        const { items } = await getItemList({
          table_id: tableId,
          filter: {
            and: [
              {
                field: mainFieldId,
                query: {
                  in: [linkedOrder],
                },
              },
            ],
          },
        });
        const item_ids = items.map((item) => {
          return item.item_id;
        });
        await delItems({ table_id: tableId, item_ids });
      }),
    );
    const requestParamses = Object.keys(thirdFields).map<UpdateItemsRequest>(
      (tableId) => {
        const updateTimeFieldId = findFieldId(tableId, ExtraFields.UpdateTime);
        const mainFieldId = findFieldId(tableId, ExtraFields.MainFieldId);
        return {
          items: thirdFields[tableId].map((item) => {
            return {
              fields: {
                ...(mainFieldId !== undefined && {
                  [mainFieldId]: [linkedOrder],
                }),
                ...(updateTimeFieldId !== undefined && {
                  [updateTimeFieldId]: dayjs().format('YYYY-MM-DD HH:mm'),
                }),
                ...item,
              },
            };
          }),
          table_id: tableId,
          update_by_fields: [mainFieldId],
          update_type: UpdateType.Upsert,
        };
      },
    );
    function findFieldId(tableId: string, extraField: ExtraFields) {
      return fieldConfigMapRef.current[extraField]?.find((item) => {
        return item.thirdField.tableId === tableId;
      })?.thirdField.fieldId;
    }
    await Promise.all(
      (requestParamses as UpdateItemsRequest[]).map(async (item) => {
        await updateItems(item);
      }),
    );
    console.log({ requestParamses });
    console.log('syncData success');
    message.success('同步数据成功');
  }
  return (
    <>
      <Flex
        gap="small"
        align="middle"
        justify="stretch"
        className="site-button-ghost-wrapper"
      >
        <Button block type="primary" onClick={onTransformData}>
          开始转换
        </Button>
        <Button block type="primary" onClick={onSyncData}>
          同步数据
        </Button>
      </Flex>
    </>
  );
}
